# coding: utf-8

from django.db import models
from django.contrib.contenttypes.models import ContentType
from django.contrib.contenttypes import generic
from django.contrib.auth.models import User
from gettext import gettext as _


class IFormManager(models.Manager):
    def get_forms(self, user):
        return self.get_query_set().filter(user=user)


class IForm(models.Model):
    name = models.CharField(_(u"Название"), max_length=75, help_text=_(u"Наименование формы"))
    owner = models.ForeignKey(User, verbose_name=_(u"Владелец"), related_name="forms")
    create_date = models.DateField(_(u"Дата создания"), auto_now_add=True )
    modify_date = models.DateField(_(u"Дата изменения"), auto_now=True )

    object = IFormManager()

    def __unicode__(self):
        return self.name

    class Meta:
        verbose_name = _(u"Форма")
        verbose_name_plural = _(u"Форма")

class IFormFieldManager(models.Manager):
    def get_fields(self):
        return self.get_query_set().filter(visible=True)

class IFormField(models.Model):

    form = models.ForeignKey(IForm, verbose_name=_(u"Форма"), related_name="fields")
    content_type = models.ForeignKey(ContentType)
    object_id = models.PositiveIntegerField()
    content_object = generic.GenericForeignKey('content_type', 'object_id')
    order = models.IntegerField(_(u"Порядок"), default=0)

    # Общие данные поля

    name = models.CharField(_(u"Название поля"), max_length=150)
    visible = models.BooleanField(_(u"Видимость поля"), default=True)

    objects = IFormFieldManager()

    class Meta:
        verbose_name = _(u"Поле")
        verbose_name_plural = _(u"Поля")
        ordering = ["order"]


class IFormTextField(models.Model):

    constructor_template = "fields/constructors/form_text_field.html"

    ifield = generic.GenericRelation(IFormField) #object_id_field="object_pk")
    default = models.TextField(_(u"Значение по умолчанию"), blank=True, default="")

    class Meta:
        verbose_name = _(u"Текстовое поле")
        verbose_name_plural = _(u"Текстовые поля")

class IFormMultilineTextField(IFormTextField):

    constructor_template = "fields/constructors/form_multiline_text_field.html"

    class Meta:
        verbose_name = _(u"Многострочное текстовое поле")
        verbose_name_plural = _(u"Многострочное текстовое поле")


class IFormBooleanField(models.Model):

    constructor_template = "fields/constructors/form_boolean_field.html"

    ifield = generic.GenericRelation(IFormField)
    default = models.BooleanField(_(u"Значение по умолчанию"), default=False)
    name_True = models.CharField(_(u"Текст для Да"), blank=True, default="", max_length=50)
    name_False = models.CharField(_(u"Текст для Нет"), blank=True, default="", max_length=50)
    show_as_radio = models.BooleanField(_(u"Показывать в виде точек"), default=False)

    class Meta:
        verbose_name = _(u"Поле Да/Нет")
        verbose_name_plural = _(u"Поля Да/Нет")